/** 
 * @CopyRight (c) 2012-2012
 * @Company <江苏瑞德信息技术有限公司>
 * @Project <eshop>
 * @JDK_Version_Used:<JDK1.6>
 * @Description:TODO<描述用途>
 * @Title: MoidfyWeb.java
 * @Author: <何俊>
 * @Author_of_Contact <E:azj1001@sina.com T:18651831939>
 * @Date 2012-11-15 上午10:00:34
 * @Modified_By: <修改人>
 * @Modified_of_Contact <修改人联系方式>
 * @Modified_Date <修改日期时间>
 * @Why & What is modified <修改原因描述>
 * @Version v1.00
 */
package com.e.buy.web.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.commons.dbclient.Batchs;
import cn.commons.exception.proxy.AzjSqlExceptionProxy;
import cn.commons.query.ConditionBean;

import com.e.buy.BuyTools;
import com.e.buy.bean.back.manager.CmiAdminUser;
import com.e.buy.bean.back.manager.cmi_ad.CmiAd;
import com.e.buy.bean.back.manager.cmi_ad.CmiAdLocation;
import com.e.buy.bean.back.manager.cmi_ad.CmiAdType;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoodsBrand;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoodsCategroy;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoodsProperties;
import com.e.buy.bean.back.manager.cmi_goods.CmiGoodsVariety;
import com.e.buy.bean.back.manager.cmi_news.CmiNews;
import com.e.buy.bean.back.manager.cmi_news.CmiNewsType;
import com.e.buy.bean.back.manager.cmi_power.CmiRole;
import com.e.buy.bean.back.manager.cmi_sigle.CmiSingle;
import com.e.buy.bean.back.manager.cmi_sigle.CmiSingleType;
import com.e.buy.enums.Commons;
import com.e.buy.enums.Status;
import com.e.buy.service.CommonsServiceClient;

/**
 * @Description:TODO(描述类别作用)
 * @author <何俊>
 * @date 2012-11-15 上午10:00:34
 * @version v1.0
 * @Other :@see #Files
 */
@Controller
@RequestMapping("/impl_modify")
public class AdminMoidfyWeb extends BuyTools {

	@Resource
	private CommonsServiceClient commons = null;

	public void setCommons(CommonsServiceClient commons) {
		this.commons = commons;
	}

	/**
	 * @Description:<后台的修改操作：修改验证操作人的session>
	 * @title: backModify
	 * @param data
	 * @param status
	 * @param session
	 * @return String 返回类型
	 * @throws
	 */
	@ResponseBody
	@RequestMapping("/backModify.adm")
	public String backModify(@RequestParam("dt") String datas, @RequestParam("st") String status,
			@RequestParam("qy") String qy, HttpSession session) {

		JSONObject json = new JSONObject();
		CmiAdminUser admin = ((CmiAdminUser) session.getAttribute("loginAdmin"));
		String msg = this.getWebProperties("web", "msg.success");
		int errorCode = 0;

		Commons.BackProcess e = Commons.getBackProcess(status);
		Object[] args = new Object[0];
		List<ConditionBean> beans = new ArrayList<ConditionBean>();
		boolean hasDone = false;
		String doWhatMsg = null;
		Status state = Status.MODIFY;
		String sql = null;
		List<Batchs> batchs = null;
		List<Object[]> batchArgs = null;
		CmiAdminUser user = null;

		/*
		 * Execute
		 */
		try {
			doWhatMsg = this.getWebProperties("web", e.getStatus() + ".MODIFY.log");
			sql = commons.getEnumSql(e, state);
			switch (e) {
			case ADMIN_MODIFY_PERSONER:
				/* Set DBParam */
				user = (CmiAdminUser) toolsbox.jsonstr2Object(datas, CmiAdminUser.class);
				args = new Object[] { user.getAid(), user.getAmail(), "", admin.getUuid() };
				doWhatMsg = this.getWebProperties("web", "adminlogin.modify.personer");
				doWhatMsg = doWhatMsg.replace("${sys}", admin.getAid()).replace("${u}", admin.getAid());
				if (isEmptyStr(user.getApass())) {
					args[2] = admin.getApass();
				} else {
					args[2] = user.getApass();
					admin.setApass(user.getApass());
				}
				sql = commons.getEnumSql(e, state);
				break;
			case ADMIN_POWER_CMI_ROLE:
				// 参数
				hasDone = true;
				CmiRole role = (CmiRole) toolsbox.jsonstr2Object(datas, CmiRole.class);
				batchs = new ArrayList<Batchs>();
				batchArgs = new ArrayList<Object[]>();
				doWhatMsg = doWhatMsg + "[" + role.getRoleName() + "]";

				// 修改角色信息
				batchArgs.add(new Object[] { role.getRoleName(), role.getRoleDesc(), role.getUuid() });
				batchs.add(new Batchs(commons.getEnumSql(e, state), batchArgs));

				// 删除已有权限
				batchArgs = new ArrayList<Object[]>();
				beans = new ArrayList<ConditionBean>();
				beans.add(new ConditionBean("roleid", "=", "?", role.getUuid() + "", "cmi_role_power"));
				batchArgs.add(service.unionConditionBeanArgs(beans));
				sql = commons.getEnumSql(Commons.BackProcess.ADMIN_POWER_CMI_ROLE_POWER, Status.REMOVE);
				batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));

				// 重新分配角色权限
				batchArgs = new ArrayList<Object[]>();
				beans = new ArrayList<ConditionBean>();
				beans.add(new ConditionBean("s.uuid", "customer", "s.uuid IN (" + role.getRolePower() + ")", "0", null));
				batchArgs.add(service.unionConditionBeanArgs(beans, role.getRoleName()));
				sql = commons.getEnumSql(Commons.BackProcess.ADMIN_POWER_CMI_ROLE_POWER, Status.ADD);
				batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));

				// 执行
				service.executeBatchSQL(batchs);
				break;
			case ADMIN_INFO:
				// 参数
				hasDone = true;
				batchs = new ArrayList<Batchs>();
				user = (CmiAdminUser) toolsbox.jsonstr2Object(datas, CmiAdminUser.class);
				doWhatMsg = doWhatMsg + "[" + user.getAid() + "]";

				// 修改管理员信息
				batchArgs = new ArrayList<Object[]>();
				beans = new ArrayList<ConditionBean>();
				batchArgs.add(new Object[] { user.getAid(), user.getAmail(), user.getApass(), user.getRoleId(),
						user.getUuid() });
				sql = commons.getEnumSql(e, state);
				batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));

				// 删除已有权限
				batchArgs = new ArrayList<Object[]>();
				beans = new ArrayList<ConditionBean>();
				beans.add(new ConditionBean("adminid", "=", "?", user.getUuid() + "", null));
				batchArgs.add(service.unionConditionBeanArgs(beans));
				sql = commons.getEnumSql(Commons.BackProcess.ADMIN_INFO_POWER, Status.REMOVE);
				batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));

				// 重新分配权限
				if (user.getRoleId() > 0) {
					batchArgs = new ArrayList<Object[]>();
					beans = new ArrayList<ConditionBean>();
					beans.add(new ConditionBean("uuid", "customer",
							"EXISTS(SELECT 1 FROM cmi_role_power p WHERE p.roleid = " + user.getRoleId()
									+ " AND p.sysid = s.uuid)", "0", null));
					batchArgs.add(service.unionConditionBeanArgs(beans, user.getAid()));
					sql = commons.getEnumSql(Commons.BackProcess.ADMIN_INFO_POWER, Status.ADD);
					batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));
				}

				// 执行
				service.executeBatchSQL(batchs);
				json.element("saveRecord", datas);
				break;
			case ADMIN_INFO_POWER:
				// 参数
				hasDone = true;
				batchs = new ArrayList<Batchs>();
				user = (CmiAdminUser) toolsbox.jsonstr2Object(datas, CmiAdminUser.class);
				doWhatMsg = doWhatMsg + "[" + user.getAid() + "]";

				// 删除已有权限
				batchArgs = new ArrayList<Object[]>();
				beans = new ArrayList<ConditionBean>();
				beans.add(new ConditionBean("adminid", "customer",
						"adminid in (SELECT u.uuid FROM cmi_admin_user u WHERE u.aid = '" + user.getAid() + "')", user
								.getAid(), null));
				batchArgs.add(service.unionConditionBeanArgs(beans));
				sql = commons.getEnumSql(e, Status.REMOVE);
				batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));

				// 重新分配权限
				batchArgs = new ArrayList<Object[]>();
				beans = new ArrayList<ConditionBean>();
				beans.add(new ConditionBean("s.uuid", "customer", "s.uuid IN (" + user.getPowerStr() + ")", "0", null));
				batchArgs.add(service.unionConditionBeanArgs(beans, user.getAid()));
				sql = commons.getEnumSql(e, Status.ADD);
				batchs.add(new Batchs(service.unionConditionBeanSql(beans, sql), batchArgs));

				// 执行
				service.executeBatchSQL(batchs);
				break;
			case GOODS_CATEGROY:
				CmiGoodsCategroy c = (CmiGoodsCategroy) toolsbox.jsonstr2Object(datas, CmiGoodsCategroy.class);
				args = new Object[] { c.getCategroy(), c.getGroups(), c.getUuid() };
				doWhatMsg = doWhatMsg + "[" + c.getCategroy() + "]";
				break;
			case GOODS_CATEGROY_PROPERTIES:
				CmiGoodsProperties p = (CmiGoodsProperties) toolsbox.jsonstr2Object(datas, CmiGoodsProperties.class);
				args = new Object[] { p.getProName(), p.getCategroyId(), p.getGroups(), p.getSearchAble(),
						p.getRelationAble(), p.getChoseAble(), p.getInputs(), p.getValueList(), p.getPsort(),
						p.getUuid() };
				doWhatMsg = doWhatMsg + "[类型:" + p.getCategroyId() + " 属性:" + p.getProName() + "]";
				break;
			case GOODS_BRAND:
				CmiGoodsBrand b = (CmiGoodsBrand) toolsbox.jsonstr2Object(datas, CmiGoodsBrand.class);
				args = new Object[] { b.getBrandName(), b.getBrandNet(), b.getBrandLogo(), b.getBrandDesc(),
						b.getBrandSort(), b.getBrandShow(), b.getUuid() };
				doWhatMsg = doWhatMsg + "[" + b.getBrandName() + "]";
				break;
			case GOODS_VARIETY:
				CmiGoodsVariety v = (CmiGoodsVariety) toolsbox.jsonstr2Object(datas, CmiGoodsVariety.class);
				args = new Object[] { v.getVarName(), v.getVarUp(), v.getVarUnit(), v.getVarSort(), v.getVarShow(),
						v.getVarNav(), v.getVarHome(), v.getVarProp(), v.getVarPrice(), v.getVarCss(),
						v.getVarKeyword(), v.getVarDesc(),v.getUuid()};
				doWhatMsg = doWhatMsg + "[" + v.getVarName() + "]";
				break;
			case NEWS_TYPE:
				CmiNewsType n = (CmiNewsType) toolsbox.jsonstr2Object(datas, CmiNewsType.class);
				args = new Object[] { n.getName(), n.getIdx(),n.getUuid()};
				doWhatMsg = doWhatMsg + "[" + n.getName() + "]";
				break;
			case SINGLE_TYPE:
				CmiSingleType s = (CmiSingleType) toolsbox.jsonstr2Object(datas, CmiSingleType.class);
				args = new Object[] { s.getName(), s.getIdx(),s.getUuid()};
				doWhatMsg = doWhatMsg + "[" + s.getName() + "]";
				break;
			case AD_TYPE:
				CmiAdType at = (CmiAdType) toolsbox.jsonstr2Object(datas, CmiAdType.class);
				args = new Object[] { at.getName(), at.getTypeDesc(),at.getUuid()};
				doWhatMsg = doWhatMsg + "[" + at.getName() + "]";
				break;
			case AD_LOC:
				CmiAdLocation al = (CmiAdLocation) toolsbox.jsonstr2Object(datas, CmiAdLocation.class);
				args = new Object[] { al.getName(), al.getWidth(),al.getHeight(),al.getLocDesc(),al.getUuid()};
				doWhatMsg = doWhatMsg + "[" + al.getName() + "]";
				break;
			default:
				errorCode = 99;
				msg = this.getWebProperties("web", "msg.fail.undefiend.status");
				break;
			}

			if (!hasDone) {
				service.executeSQL(sql, args);
			}
			try {
				commons.noteAdminLog(doWhatMsg, admin.getUuid());
			} catch (Exception ex) {
			}
		} catch (Exception ex) {
			log4j.error("Modify Datas Exception:" + ex);
			try {
				AzjSqlExceptionProxy p = new AzjSqlExceptionProxy(ex);
				errorCode = p.getErrorCode();
				// 唯一键存在重复项
				if (errorCode == 1062) {
					msg = this.getWebProperties("web", e.getStatus() + ".1062");
				} else {
					errorCode = 100;
					msg = this.getWebProperties("web", "msg.fail");
				}
			} catch (Exception e2) {
				errorCode = 100;
				msg = this.getWebProperties("web", "msg.fail");
			}
		}
		json.element("error", errorCode);
		json.element("msg", msg);
		return json.toString();
	}

	@ResponseBody
	@RequestMapping("/backFileUploadModify.adm")
	public String backFileUploadModify(HttpServletRequest req, HttpSession session,
			@RequestParam("file") MultipartFile[] file, @RequestParam("dt") String datas,
			@RequestParam("st") String status, @RequestParam("qy") String qy) {

		JSONObject json = new JSONObject();
		CmiAdminUser admin = ((CmiAdminUser) session.getAttribute("loginAdmin"));
		String msg = this.getWebProperties("web", "msg.success");
		int errorCode = 0;

		Commons.BackProcess e = Commons.getBackProcess(status);
		Object[] args = new Object[0];
//		List<ConditionBean> beans = new ArrayList<ConditionBean>();
		boolean hasDone = false;
		String doWhatMsg = null;
		Status state = Status.MODIFY;
		String sql = null;
//		List<Batchs> batchs = null;
//		List<Object[]> batchArgs = null;
//		CmiAdminUser user = null;

		/*
		 * Execute
		 */
		try {
			doWhatMsg = this.getWebProperties("web", e.getStatus() + ".MODIFY.log");
			sql = commons.getEnumSql(e, state);
			switch (e) {
			case GOODS_BRAND:
				CmiGoodsBrand b = (CmiGoodsBrand) toolsbox.jsonstr2Object(datas, CmiGoodsBrand.class);
				MultipartFile f = file[0];
				String savePath = "/data/brandlogo/" + toolsbox.getJavaUUID();
				boolean save = true;
				long brandlogoSize = f.getSize();
				String brandlogoName = f.getOriginalFilename();
				String webapp = req.getSession().getServletContext().getRealPath("/");
				if(brandlogoSize == 0 && StringUtils.isEmpty(brandlogoName)){
					b.setBrandLogo(b.getLastBrandlogo());
				} else {
					// 获取请求的本地路径
					if(isEmptyStr(b.getLastBrandlogo())){
						String sufix = brandlogoName.substring(brandlogoName.lastIndexOf("."));
						savePath = savePath + sufix;
					} else {
						savePath = b.getLastBrandlogo();
					}
					save = this.writUploadPic(f.getInputStream(), webapp + savePath);
					b.setBrandLogo(savePath);
				}
				if(save) {
					log4j.debug("Modify---save upload file in [" + webapp + savePath + "]");
					args = new Object[] { b.getBrandName(), b.getBrandNet(), b.getBrandLogo(), b.getBrandDesc(),
							b.getBrandSort(), b.getBrandShow(),b.getUuid()};
					doWhatMsg = doWhatMsg + "[" + b.getBrandName() + "]";
				}
				break;
			case NEWS:
				CmiNews news = (CmiNews) toolsbox.jsonstr2Object(datas, CmiNews.class);
				MultipartFile newsF = file[0];
				String newsSavePath = "/data/news/" + toolsbox.getJavaUUID();
			    boolean newsSave = true;
				long newsImgSize = newsF.getSize();
				String newsImgName = newsF.getOriginalFilename();
				webapp = req.getSession().getServletContext().getRealPath("/");
				
				if (newsImgSize == 0 && StringUtils.isEmpty(newsImgName)) {
					news.setNewsImg(news.getLastNewsImg());
				} else {
							// 获取请求的本地路径
					if(isEmptyStr(news.getLastNewsImg())){
						String sufix = newsImgName.substring(newsImgName.lastIndexOf("."));
						newsSavePath =newsSavePath + sufix;
					} else {
						newsSavePath = news.getLastNewsImg();
					}
					newsSave = this.writUploadPic(newsF.getInputStream(), webapp + newsSavePath);
					news.setNewsImg(newsSavePath);
				}
				if (newsSave) {
					log4j.debug("Add--save upload file in [" + webapp + newsSavePath + "]");
					args = new Object[] { news.getNewsTitle(), news.getTypeId(), news.getNewsSrc(), news.getNewsImg(), news.getCreateTime(),
							news.getNewsRec(), news.getSummary(),news.getContent(),news.getOrderNum(),news.getUuid() };
					doWhatMsg = doWhatMsg + "[" + news.getNewsTitle() + "]";
				}
				break;
			case SINGLE:
				CmiSingle single = (CmiSingle) toolsbox.jsonstr2Object(datas, CmiSingle.class);
				MultipartFile singleF = file[0];
				String singleSavePath = "/data/single/" + toolsbox.getJavaUUID();
			    boolean singleSave = true;
				long singleImgSize = singleF.getSize();
				String singleImgName = singleF.getOriginalFilename();
				webapp = req.getSession().getServletContext().getRealPath("/");
				
				if (singleImgSize == 0 && StringUtils.isEmpty(singleImgName)) {
					single.setImg(single.getLastImg());
				} else {
							// 获取请求的本地路径
					if(isEmptyStr(single.getLastImg())){
						String sufix = singleImgName.substring(singleImgName.lastIndexOf("."));
						singleSavePath =singleSavePath + sufix;
					} else {
						singleSavePath = single.getLastImg();
					}
					singleSave = this.writUploadPic(singleF.getInputStream(), webapp + singleSavePath);
					single.setImg(singleSavePath);
				}
				if (singleSave) {
					log4j.debug("Add--save upload file in [" + webapp + singleSavePath + "]");
					args = new Object[] { single.getName(), single.getTypeId(), single.getImg(), single.getContent(),
							single.getIsRec(), single.getIdx(),single.getUuid()};			
					doWhatMsg = doWhatMsg + "[" + single.getName() + "]";
				}
				break;
			case AD:
				CmiAd ad = (CmiAd) toolsbox.jsonstr2Object(datas, CmiAd.class);
				MultipartFile adF = file[0];
				String adSavePath = "/data/ad/" + toolsbox.getJavaUUID();
			    boolean adSave = true;
				long adImgSize = adF.getSize();
				String adImgName = adF.getOriginalFilename();
				webapp = req.getSession().getServletContext().getRealPath("/");
				
				if (adImgSize == 0 && StringUtils.isEmpty(adImgName)) {
					ad.setAdImg(ad.getLastImg());
				} else {
							// 获取请求的本地路径
					if(isEmptyStr(ad.getLastImg())){
						String sufix = adImgName.substring(adImgName.lastIndexOf("."));
						adSavePath =adSavePath + sufix;
					} else {
						adSavePath = ad.getLastImg();
					}
					adSave = this.writUploadPic(adF.getInputStream(), webapp + adSavePath);
					ad.setAdImg(adSavePath);
				}
				if (adSave) {
					log4j.debug("Add--save upload file in [" + webapp + adSavePath + "]");
					args = new Object[] { ad.getName(), ad.getAdType(), ad.getAdLocId(), ad.getStartTime(),
							ad.getEndTime(), ad.getLink(),ad.getAdImg(),ad.getImgLink(),ad.getContractUser(),ad.getContractEmail(),ad.getContractPhone(),ad.getEnable(),ad.getUuid()};
					doWhatMsg = doWhatMsg + "[" + ad.getName() + "]";
				}
				break;
			default:
				errorCode = 99;
				msg = this.getWebProperties("web", "msg.fail.undefiend.status");
				break;
			}

			if (!hasDone) {
				service.executeSQL(sql, args);
			}
			try {
				commons.noteAdminLog(doWhatMsg, admin.getUuid());
			} catch (Exception ex) {
			}
		} catch (Exception ex) {
			log4j.error("Modify Datas Exception:" + ex);
			try {
				AzjSqlExceptionProxy p = new AzjSqlExceptionProxy(ex);
				errorCode = p.getErrorCode();
				// 唯一键存在重复项
				if (errorCode == 1062) {
					msg = this.getWebProperties("web", e.getStatus() + ".1062");
				} else {
					errorCode = 100;
					msg = this.getWebProperties("web", "msg.fail");
				}
			} catch (Exception e2) {
				errorCode = 100;
				msg = this.getWebProperties("web", "msg.fail");
			}
		}
		json.element("error", errorCode);
		json.element("msg", msg);
		return json.toString();
	}
}
